<?php

namespace frontend\modules\wechat\controllers;

use common\models\sys\SysSetting;
use common\models\wechat\WechatAccounts;
use common\models\wechat\WechatFans;
use common\models\wechat\WechatReplyKeyword;
use common\models\wechat\WechatReplyRule;
use frontend\controllers\BaseController;
use yii;
class FansController extends ProcessController
{

    /**
     * 关注处理
     * @return array
     * @throws \yii\base\InvalidConfigException
     */
    public function actionSubscribe()
    {
        $fans = $this->getFans();
        if (!$fans) { // 存储粉丝信息
            $fans = Yii::createObject(WechatFans::className());

            $fans->setAttributes([
                'wid' => WechatAccounts::WID,
                'openid' => $this->message['FromUserName'],
                'follow' => WechatFans::STATUS_SUBSCRIBED,
                'followtime' => time()
            ]);

            if($this->getWechat()->level > WechatAccounts::TYPE_SUBSCRIBE){
                $data = \Yii::$app->wechat->user->get($this->message['FromUserName']);
                $fans->setAttributes([
                    'nickname' => $data->nickname,
                    'avatar' => $data->headimgurl,
                ]);
            }
            Yii::warning($fans->getErrors());
            if ($fans->save() && $data = $this->getWechat()->level > WechatAccounts::TYPE_SUBSCRIBE) { // 更新用户详细数据, 普通订阅号无权限获取
                $fans->updateUser();
            }
        } elseif ($fans->follow != WechatFans::STATUS_SUBSCRIBED) { // 更新关注状态
            $fans->subscribe();
        }

        //取出关注回复的关键字
        $kwd = SysSetting::getValue('wechat_welcome');
        $processor = WechatReplyKeyword::find()->alias('kwd')->select('rule.processor,kwd.content')
            ->leftJoin(['rule'=>WechatReplyRule::tableName()],'kwd.rid=rule.id')
            ->where(['kwd.content'=>$kwd])
            ->asArray()
            ->one();
        //回复
        if(!empty($processor)){
            Yii::$app->runAction('/wechat/reply/'.$processor['processor'],['content'=>$processor['content']]);
        }else{      //没有匹配的，直接回复设置的话语
            $server = \Yii::$app->wechat->server;
            $server->setMessageHandler(function ($message) use($kwd) {
                return $kwd;
            });
            $response = $server->serve();
            $response->send();
        }
    }

    /**
     * 取消关注处理
     */
    public function actionUnsubscribe()
    {
        if ($fans = $this->getFans()) {
            $fans->unsubscribe();
        }
    }


}
